package com.brotherly.framework.timer;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;

import com.brotherly.framework.service.IService;

public class TimerService implements IService
{
    public static final String description = "com.brotherly.framework.timer.TIMER";

    protected Map<Integer, TimerTask> tasks;

    protected Timer timer;

    @SuppressLint("UseSparseArrays")
    public TimerService()
    {
        tasks = new HashMap<Integer, TimerTask>();
        timer = new Timer(true);
    }

    public synchronized void cancel(int stub)
    {
        Integer key = Integer.valueOf(stub);

        TimerTask task = tasks.get(key);
        if (task != null)
        {
            tasks.remove(key);
            task.cancel();
        }
    }

    @Override
    public void init()
    {

    }

    public synchronized int startTimer(final TimerListener listener, int interval)
    {
        if (listener == null || interval == 0)
            return -1;

        TimerTask task = new TimerTask()
        {
            @Override
            public void run()
            {
                try
                {
                    if (!listener.isOnTask())
                    {
                        TimerService.this.cancel(this.hashCode());
                        return;
                    }
                    listener.setOnTask(true);
                    listener.onTimer();
                }
                catch (Exception e)
                {}
            }
        };

        Integer stub = Integer.valueOf(task.hashCode());
        tasks.put(stub, task);

        if (interval > 0)
        {
            timer.scheduleAtFixedRate(task, interval, interval);
        } else
        {
            interval = -interval;

            timer.schedule(task, interval);
        }

        return stub.intValue();
    }
}
